#include "timerdevice.h"
#include "error.h"

TimerDevice::TimerDevice()
{

}

TimerDevice::~TimerDevice()
{
    for(t_timerMap::iterator i = timerMap.begin(); i != timerMap.end(); i++)
    {
        delete (*i).second; // Delete dynamically allocated Timer pointers
    }

    timerMap.clear();
}


void TimerDevice::newTimer(std::string name)
{
    t_timerMap::iterator foundpos = timerMap.find(name);
    if( foundpos != timerMap.end() ) // Remove any timer by the same name
        timerMap.erase(foundpos);

    Timer *nt = new Timer;
	if( nt == NULL )
		allocationError();
    timerMap[name] = nt;
}

int TimerDevice::removeTimer(std::string name)
{
    t_timerMap::iterator foundpos = timerMap.find(name);
    if( foundpos != timerMap.end() ){ // Remove any timer by the same name
        timerMap.erase(foundpos);
        return true; }
    else
        return false;
}

int TimerDevice::startTimer(std::string name, double trigger)
{
    t_timerMap::iterator foundpos = timerMap.find(name);
    if( foundpos != timerMap.end() ) {
        foundpos->second->start(trigger);
        return true; }
    else
        return false;
}

int TimerDevice::isTriggered(std::string name)
{
    t_timerMap::iterator foundpos = timerMap.find(name);
    if( foundpos != timerMap.end() )
    {
        int result = foundpos->second->triggered();
        return result;
    }
    else
        return false; // Not found, assume false
}
